package com.wxq.utility;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.PorterDuff;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.Window;

public class QUtility {
	public static String shopfun_version=null;
	public static String address = null;
	public static String port = null;
	
public static void copyFile(String from,String to) {
    	
        FileInputStream  fis = null;
        FileOutputStream fos = null;
        //File file = new File(android.os.Environment.getExternalStorageDirectory()+"/serverconf.xml");
		try 
		{
			fis = new FileInputStream(from);
			fos = new FileOutputStream(to);
			byte [] buffer = new byte[8192];
			
			int count = 0;
			while((count = fis.read(buffer))>=0)
			{
				fos.write(buffer, 0, count);
			}
			fos.close();
			fis.close();
		} catch (IOException e) {
			Log.d("wxq", "Can NOT copy the file:"+from);
			e.printStackTrace();
		}
	}

	public static void copyFileFromAssets(Context context,String fileInAssets,File outFile) {
    	AssetManager am = context.getAssets();
        InputStream is;
        FileOutputStream fos = null;
        //File file = new File(android.os.Environment.getExternalStorageDirectory()+"/serverconf.xml");
		try 
		{
			is = am.open(fileInAssets);
			fos = new FileOutputStream(outFile);
			byte [] buffer = new byte[8192];
			
			int count = 0;
			while((count = is.read(buffer))>=0)
			{
				fos.write(buffer, 0, count);
			}
			fos.close();
			is.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.d("wxq", "Can NOT copy the file:"+outFile.getName());
			e.printStackTrace();
		}
	}
	public static void copyFileFromAssets(Context context,String fileInAssets,String outFileName) {
		File outFile = new File(outFileName);
		copyFileFromAssets(context, fileInAssets, outFile);
	}
	
	public static boolean CreateFile(String destFileName) {
	    File file = new File(destFileName);
	    if (file.exists()) {
	    	System.out.println("创建单个文件" + destFileName + "失败，目标文件已存在！");
	    	return false;
	    }
	    if (destFileName.endsWith(File.separator)) {
	    	System.out.println("创建单个文件" + destFileName + "失败，目标不能是目录！");
	    	return false;
	    }
	    if (!file.getParentFile().exists()) {
	    	System.out.println("目标文件所在路径不存在，准备创建。。。");
	     if (!file.getParentFile().mkdirs()) {
	    	 System.out.println("创建目录文件所在的目录失败！");
	    	 return false;
	     }
	    }

	    // 创建目标文件
	    try {
	     if (file.createNewFile()) {
	    	 System.out.println("创建单个文件" + destFileName + "成功！");
	    	 return true;
	     } 
	     else {
	    	 System.out.println("创建单个文件" + destFileName + "失败！");
	    	 return false;
	     }
	    } 
	    catch (IOException e) {
	    	e.printStackTrace();
	    	System.out.println("创建单个文件" + destFileName + "失败！");
	    	return false;
	    }
	}
	
	public static boolean createDir(String destDirName) {
	    File dir = new File(destDirName);
	    if(dir.exists()) {
	    	System.out.println("创建目录" + destDirName + "失败，目标目录已存在！");
	    	return false;
	    }
	    if(!destDirName.endsWith(File.separator))
	    	destDirName = destDirName + File.separator;
	    // 创建单个目录
	    if(dir.mkdirs()) {
	    	System.out.println("创建目录" + destDirName + "成功！");
	    	return true;
	    } else {
	    	System.out.println("创建目录" + destDirName + "失败！");
	    	return false;
	    }
	}
    
    public static void getServerConf(String fileName) {
		File file = new File(fileName);
		if(!file.exists())
		{
			QLog.d("wxq", "conf file does NOT exists!");
			return;
		}
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		getServerConf(fis);
	}
    public static void getServerConf(InputStream inputStream) {
    	if(inputStream == null)
    	{
    		QLog.d("wxq", "inputStream is null");
    		return ;
    	}
    	try {
        	XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            factory.setNamespaceAware(true);
            XmlPullParser parser = factory.newPullParser();
            parser.setInput(inputStream, null);
            //Resources res = this.getResources();
            //XmlResourceParser  parser = res.getXml(R.xml.serverconf);
			parser.next();
			int eventType = parser.getEventType();
			String TagName = "";
			String TagValue = "";
			while (eventType != XmlPullParser.END_DOCUMENT)
			{
				if(eventType == XmlPullParser.START_DOCUMENT)
				{
				   
				}
				else if(eventType == XmlPullParser.START_TAG)
				{
					TagName = parser.getName();
				}
				else if(eventType == XmlPullParser.END_TAG)
				{
					TagName = parser.getName();
					if(TagName.equals("address"))
					{
						QLog.d("wxq", "address="+TagValue);
						address = TagValue;
					}
					else if(TagName.equals("port"))
					{
						QLog.d("wxq", "port="+TagValue);
						port = TagValue;
					}
				}
				else if(eventType == XmlPullParser.TEXT)
				{
					TagValue = parser.getText();
				}
				eventType = parser.next();
			}//eof-while
			if(inputStream!=null)
			{
				inputStream.close();
			}
			
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
    
    public static Map<String, String> getMoreInfoMap(String xmlContent) {
		Map<String, String> map = new HashMap<String, String>();
		if (TextUtils.isEmpty(xmlContent)) {
			return map;
		}
		try {
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
	         factory.setNamespaceAware(true);
	         XmlPullParser xpp = factory.newPullParser();
	         xpp.setInput( new StringReader ( xmlContent ) );
	         
	         int eventType = xpp.getEventType();
	         String tagName = null;
	         String tagValue = null;
	         
	         while (eventType != XmlPullParser.END_DOCUMENT) {
	          if(eventType == XmlPullParser.START_DOCUMENT) {
	        	  //Log.d("wxq", "分析moreInfo开始！");
	          } else if(eventType == XmlPullParser.START_TAG) {
	              tagName = xpp.getName();
	          } else if(eventType == XmlPullParser.END_TAG) {
	              if(! xpp.getName().equals("Unit"))
	              {
	            	  map.put(tagName, tagValue);
	              }
	          } else if(eventType == XmlPullParser.TEXT) {
	              tagValue = xpp.getText();
	          }
	          eventType = xpp.next();
	         }
	         //System.out.println("End document");
	         //Log.d("wxq", "分析moreInfo完毕！");
			
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return map;
	}
    
    /*
     * get the view's size info
     */
    public static void  displayViewSize(View v) {
		QLog.d("view:"+v.getId()+
				",left="+v.getLeft()+
				",top="+v.getTop()+
				",width="+v.getWidth()+
				",height="+v.getHeight());
	}
    
    /*
     * get the window's size info
     */
    public static void displayWindowSize(Context context) {
    	//get display ,this is the whole window that include status bar and app's title bar ,
        //display will not change after run
        Display d = ((Activity) context).getWindowManager().getDefaultDisplay();
        QLog.d("window:"+
        		",width="+d.getWidth()+
        		",height="+d.getHeight());
	}
    
    /*
     * get the app's size info
     */
    public static void displayAppSize(Context context) {
    	//get the rect of the app's decorView ,include title bar,
        //decorView will change after run
        Rect appFrame = new Rect();
		((Activity) context).getWindow().getDecorView().getWindowVisibleDisplayFrame(appFrame);
		QLog.d( "appFrame:"+
				",left="+appFrame.left+
				",top="+appFrame.top+
				",width="+appFrame.width()+
				",height="+appFrame.height());
	}
    
    /*
     * get the ContentView's size
     */
    public static void displayContentViewSize(Context context) {
    	//get main content View, only the root layout that user define
    	//this will change after run
    	View contentView = ((Activity) context).getWindow().findViewById(Window.ID_ANDROID_CONTENT);
    	QLog.d("ContentView:"+contentView.getId()+
    			",left="+contentView.getLeft()+
    			",top="+contentView.getTop()+
    			",width="+contentView.getWidth()+
    			",height="+contentView.getHeight()
    	);
	}
    
    /*
     * get all of the app's size info,include window,app,contentView
     */
    public static void displaySize(Context context) {
        
        displayWindowSize(context);
        
        displayAppSize(context);
		
		displayContentViewSize(context);
		
	}
    
    public static Bitmap getBitmapWithName(Context context, String name) {
		ApplicationInfo appInfo = context.getApplicationInfo();
		int resID = context.getResources().getIdentifier(name, "drawable", appInfo.packageName);
		return BitmapFactory.decodeResource(context.getResources(), resID);
	}
    
    public static void startActivity(Context from, Class<?> to)
    {
    	Intent intent = new Intent();
		intent.setClass(from, to);
		from.startActivity(intent);
    }
    public static Bitmap getRoundedCornerBitmap(Context context, Bitmap input, int pixels , int w , int h , 
    											boolean squareTL, boolean squareTR, boolean squareBL, boolean squareBR  ) 
    {      Bitmap output = Bitmap.createBitmap(w, h, Config.ARGB_8888);     
    	   Canvas canvas = new Canvas(output);     
    	   final float densityMultiplier = context.getResources().getDisplayMetrics().density;      
    	   final int color = 0xff424242;     
    	   final Paint paint = new Paint();     
    	   final Rect rect = new Rect(0, 0, w, h);     
    	   final RectF rectF = new RectF(rect);      //make sure that our rounded corner is scaled appropriately     
    	   final float roundPx = pixels*densityMultiplier;      
    	   paint.setAntiAlias(true);     
    	   canvas.drawARGB(0, 0, 0, 0);     
    	   paint.setColor(color);     
    	   canvas.drawRoundRect(rectF, roundPx, roundPx, paint);       //draw rectangles over the corners we want to be square     
    	   if (squareTL )
    	   {         
    		   canvas.drawRect(0, 0, w/2, h/2, paint);     
    	   }     
    	   if (squareTR )
    	   {         
    		   canvas.drawRect(w/2, 0, w, h/2, paint);     
    	   }     
    	   if (squareBL )
    	   {         
    		   canvas.drawRect(0, h/2, w/2, h, paint);     
    	   }     
    	   if (squareBR )
    	   {         
    		   canvas.drawRect(w/2, h/2, w, h, paint);    
    	   }      
    	   paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));     
    	   canvas.drawBitmap(input, 0,0, paint);      
    	   return output; 
    	  
    }
    
    public  static String getFromatTime(String dateString,SimpleDateFormat mSinaWeiboDateFormat) 
    {
        if ( dateString != null && !"".equals(dateString)) 
        {
            try 
            {
                Date date = mSinaWeiboDateFormat.parse(dateString);
                int second = (int)(System.currentTimeMillis() - date.getTime())/1000;
                if (second > 59 && second < 1800) {
                    return (second/60 + "分钟前");
                } else if (second < 59) {
                    return (second + "秒前");
                } else {
                	SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("MM-dd hh:mm");
                    return (mSimpleDateFormat.format(date)+"");
                }
            } 
            catch (ParseException e) 
            {
                e.printStackTrace();
            }
        } 
        else 
        {
            return "";
        }
        return "";
	}
    
    public static String getWeiboSource(String str) {
		String source = "";
		InputStream is = new ByteArrayInputStream(str.getBytes());
		source = getWeiboSource(is);
		return source;
	}
    
    public static String getWeiboSource(InputStream inputStream) {
    	String source = "";
    	if(inputStream == null)
    	{
    		QLog.d("wxq", "inputStream is null");
    		return source;
    	}
    	try 
    	{
        	XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            factory.setNamespaceAware(true);
            XmlPullParser parser = factory.newPullParser();
            parser.setInput(inputStream, null);
            //Resources res = this.getResources();
            //XmlResourceParser  parser = res.getXml(R.xml.serverconf);
			parser.next();
			int eventType = parser.getEventType();
			String TagName = "";
			String TagValue = "";
			while (eventType != XmlPullParser.END_DOCUMENT)
			{
				if(eventType == XmlPullParser.START_DOCUMENT)
				{
					
				}
				else if(eventType == XmlPullParser.START_TAG)
				{
					TagName = parser.getName();
				}
				else if(eventType == XmlPullParser.END_TAG)
				{
					TagName = parser.getName();
					if(TagName.equals("a"))
					{
						QLog.d("wxq", "source="+TagValue);
						source = TagValue;
					}
					
				}
				else if(eventType == XmlPullParser.TEXT)
				{
					TagValue = parser.getText();
				}
				eventType = parser.next();
			}//eof-while
			if(inputStream!=null)
			{
				inputStream.close();
			}
			
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return source;
	}
    
    /**
     * 加载本地图片
     * @param url
     * @return
     */
     public static Bitmap getLoacalBitmap(String url) {
          try {
               FileInputStream fis = new FileInputStream(url);
               return BitmapFactory.decodeStream(fis);  ///把流转化为Bitmap图片        

            } catch (FileNotFoundException e) {
               e.printStackTrace();
               return null;
          }
     }
    
}
